package yiwang.rememberdaka;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends Activity {

    private Switch checkSwitch;
    private EditText edDate;
    private EditText editName;
    private EditText editPsw;
    private EditText edIdentifyNum;
    private Button btnLogin;
    private AlarmManager alarmManager;
    private PickerView hourPV;
    private PickerView minutePV;
    private static final int TIME_INTERVAL = 1000 * 60 * 60 * 24;// 24h
    private int hourOfDay = 8;
    private int minute = 30;
    private String strHourOfDay = "08";
    private String strMinute = "30";
    private AlarmReceiver receiver;
    private SharedPreferences appInfo;
    private final static String APP_INFO = "yiwang.remember.appinfo";
    private Date mDate;

    //把字符串转为日期
    private Date converToDate(String strDate) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.parse(strDate);
    }

    /**
     * 开启定时器
     * 接受类型为广播
     */
    private void startAlarmReceiver() {
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(mDate);

        alarmManager = (AlarmManager) super.getSystemService(ALARM_SERVICE);
//        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), TIME_INTERVAL, sender);//set the properties of alarm
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
    }

    /**
     * 取消定时器
     */
    private void cancleAlarmReceiver() {
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarm.cancel(pi);
    }

    /**
     * 开启定时器
     * 接受类型为服务
     */
    private void startAlarmService(){
        Intent intent = new Intent(this, MainService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) super.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(mDate);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

    private void cancleAlarmService(){
        Intent intent = new Intent(this, MainService.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarm.cancel(pi);
    }

    /**
     * 调本地上次保存的用户信息
     */
    protected void loadUserInfo() {
        UserInfo.setUserName(appInfo.getString(UserInfo.USERNAME, UserInfo.DEFAULT_USER_NAME));
        UserInfo.setUserPassword(appInfo.getString(UserInfo.USERPWD, UserInfo.DEFAULT_USER_PWD));
        UserInfo.setIdentifyNum(appInfo.getString(UserInfo.ID, UserInfo.DEFAULT_IDENTIFY_NUM));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        appInfo = getSharedPreferences(APP_INFO, MODE_PRIVATE);
        loadUserInfo();
        initView();
    }

    /**
     * 初始化UI
     */
    private void initView() {
        edDate = (EditText) findViewById(R.id.edDate);
        hourPV = (PickerView) findViewById(R.id.hour_pv);
        minutePV = (PickerView) findViewById(R.id.minute_pv);
        editName = (EditText) findViewById(R.id.edName);
        final Map<String, Integer> hourMap = new HashMap<>();
        final Map<String, Integer> minuteMap = new HashMap<>();
        List<String> hours = new ArrayList<String>();
        List<String> minutes = new ArrayList<String>();

        for (int i = 0; i < 24; i++) {
            hours.add(i < 10 ? "0" + i : "" + i);
            hourMap.put(i < 10 ? "0" + i : "" + i, i);
        }
        for (int i = 0; i < 60; i++) {
            minutes.add(i < 10 ? "0" + i : "" + i);
            minuteMap.put(i < 10 ? "0" + i : "" + i, i);
        }

        hourPV.setData(hours);
        hourPV.setSelected(8);
        hourPV.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                hourOfDay = hourMap.get(text);
                strHourOfDay = text;
            }
        });

        minutePV.setData(minutes);
        minutePV.setSelected(30);
        minutePV.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                minute = minuteMap.get(text);
                strMinute = text;
            }
        });

        if (!isNullOrEmpty(UserInfo.getUserName())) {
            editName.setText(UserInfo.userName);
        }
        editPsw = (EditText) findViewById(R.id.edPsw);
        if (!isNullOrEmpty(UserInfo.getUserPassword())) {
            editPsw.setText(UserInfo.userPassword);
        }
        edIdentifyNum = (EditText) findViewById(R.id.edIdentifyNum);
        if (!isNullOrEmpty(UserInfo.getIdentifyNum())) {
            edIdentifyNum.setText(UserInfo.identifyNum);
        }

        checkSwitch = (Switch) findViewById(R.id.open);
        checkSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    String name = editName.getText().toString();
                    String psw = editPsw.getText().toString();
                    String identifyNum = edIdentifyNum.getText().toString();

                    String strDate = edDate.getText().toString();
                    if (isNullOrEmpty(strDate)) {
                        Toast.makeText(MainActivity.this, "请填写日期信息！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    strDate = strDate + " " + strHourOfDay + ":" + strMinute + ":" + "00";

                    try{
                        mDate = converToDate(strDate);
                    }catch (Exception e){

                    }

                    if (checkUserInfo(name, psw, identifyNum)) {
                        UserInfo.setUserName(name);
                        UserInfo.setUserPassword(psw);
                        UserInfo.setIdentifyNum(identifyNum);
                        saveUserInfo();
                        startAlarmService();
                    } else {
                        Toast.makeText(MainActivity.this, "请填写完整的用户信息！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    cancleAlarmService();
                }
            }
        });
    }

    private boolean checkUserInfo(String name, String psw, String id) {
        if (isNullOrEmpty(name) || isNullOrEmpty(psw) || isNullOrEmpty(id)) {
            return false;
        }

        return true;
    }

    private static boolean isNullOrEmpty(String str) {
        return str == null || str.trim().length() == 0 || "null".equals(str);
    }

    /**
     * 保存用户信息
     */
    protected void saveUserInfo() {
        SharedPreferences.Editor editor = appInfo.edit();
        editor.putString(UserInfo.USERNAME, UserInfo.getUserName());
        editor.putString(UserInfo.USERPWD, UserInfo.getUserPassword());
        editor.putString(UserInfo.ID, UserInfo.getIdentifyNum());
        editor.commit();
    }

}
